import { Res } from "@/api/common"
import { createFetch } from "@vueuse/core"
import { unref } from "vue"

export const adminFetch = createFetch({
    baseUrl: import.meta.env.VITE_API_ADMIN_URL,
    options: {
        // 请求前授权处理
        async beforeFetch({ url, options, cancel }) {
            // const myToken = await getMyToken()
            // options.headers.Authorization = `Bearer ${myToken}`
            return { url, options, cancel }
        },
        // 响应结果错误处理
        async afterFetch({ response, data }) {
            return { response, data }
        },
        // http响应错误处理
        async onFetchError({ data, response, error }) {
            // if (error.response.status === 401) {

            // }
            return { data, response, error }
        },
        timeout: 5000
    }
})

// get请求参数转换
export function objectToSearch(params: Record<string, any>) {
    let searchParams = '';
    if (Object.keys(params).length > 0) {
        for (const key in params) {
            const value = params[key]
            if (value !== undefined && value !== null) {
                searchParams += `${key}=${params[key]}&`;
            }
        }
        searchParams = searchParams.slice(0, searchParams.length - 1);
    }
    return searchParams;
}


export function useHandleApiRes<T = any>(promise: PromiseLike<any>): PromiseLike<Res<T>> {
    return promise.then((res) => {
        const { data } = res;
        return unref(data) || {} as Res<T>;
    });
}